FUNCTIONS

Course- C IN LINUX >

The entry point into all our programs is called main() and this is a function, or a piece of code that does something, usually returning some value. We structure programs into functions to stop them become long unreadable blocks of code than cannot be seen in one screen or page and also to ensure that we do not have repeated identical chunks of code all over the place. We can call library functions like printf or strtok which are part of the C language and we can call our own or other peoples functions and libraries of functions. We have to ensure that the appropriate header ile exists and can be read by the preprocessor and that the source code or compiled library exists too and is accessible.

As we learned before, the scope of data is restricted to the function in which is was declared, so we use pointers to data and blocks of data to pass to functions that we wish to do some work on our data. We have seen already that strings are handled as pointers to arrays of single characters terminated with a NULL character.

#include <stdio.h>
#include <string.h>
#include <math.h>

double doit(int number1, int number2)
{

return sqrt((double)(number1+number2));
}


int main(int argc, char *argv[], char *env[])

{

int n1=0, n2=0, i=0;
n1=atoi((char *) strtok(argv[1],":"));
n2=atoi((char *) strtok(NULL,":"));
printf("Content-type:text/html\n\n<html><body>\n");
for(i=1,i<=100;i++)
printf("%f",doit(n1+i,n2*i));
printf("n</html></body>\n");
return 0;


}


}                    
                    

In this example we can repeatedly call the function “doit” that takes two integer arguments and reurns the result of some mathematical calculation.

(You should be using the Makeile supplied or be maintaining a Makeile as you progress, adding targets to compile examples as you go.)

c function result

In this case the arguments to our function are sent as copies and are not modiied in the function but used.

If we want to actual modify a variable we would have to send its pointer to a function.

#include <stdio.h>
#include <string.h>
#include <math.h>

double doit(int number1, int number2, double *result)
{

*return = sqrt((double)(number1+number2));
}


int main(int argc, char *argv[], char *env[])

{

int n1=0, n2=0, i=0;
double result = 0;
n1=atoi((char *) strtok(argv[1],":"));
n2=atoi((char *) strtok(NULL,":"));
printf("Content-type:text/html\n\n<html><body>\n");
for(i=1,i<=100;i++)
{
doit(n1+i,n2*i,&result);
printf("%f",result);

}

printf("n</html></body>\n");
return 0;


}


}                    
                    

We send the address of the variable ‘result’ with &result, and in the function doit we de-reference the pointer with *result to get at the loat and change its value, outside its scope inside main. This gives identical output